$(function () {
    let $doc = $(document);
    let admin = {
        init: function () {
            this.event();
            this.editor();
        },
        event: function () {
            let that = this;
            $('.save').click(function (e) {
                e.preventDefault();
                let $this = $(this);
                let $form = $this.closest('form');
                let data = $form.serialize();
                let $action = $form.attr('action');
                $.post($action, data, function (res) {
                    that.handle(res)
                })
            });
            //通用删除
            $('.js-delete').click(function () {
                let $ele = $(this);
                that.confirm($ele);
            });
            //图库上传图片
            that.upload({
                ele: '.upload-img',
                name: 'img',
                success: function (file, res) {
                    that.handle(res);
                }
            });
            $('.img-picker').click(function (e) {
                let $picker = $(this);
                that.uploadLib({
                    text: '图片',
                    url: '/album/library',
                    paths: '',
                    number: 1,
                    callback: function (data) {
                        let $row = $picker.closest('.form-row');
                        let $img = $row.find('img');
                        if ($img.length) {
                            $row.find('img').attr('src', data[0]);
                        }
                        else {
                            $row.find('.img-preview').html(`<img src="${data[0]}">`);
                        }

                        $row.find('input:hidden').val(data[0]);
                    }
                })
            });
            $('.album-mask .del').click(function () {
                let $ele = $(this);
                that.confirm($ele);
            });

            $('.album-mask .copy').click(function () {
                let clipboard = new ClipboardJS('.copy');
                clipboard.on('success', function (e) {
                    $.tipTop(true, '复制图片地址成功')
                });
                clipboard.on('error', function (e) {
                    console.log(e);
                });

            });

            $('.js-check').click(function (e) {
                e.preventDefault();
                let url = $(this).data('url');
                let action = $(this).data('action');
                $.get(url, function (res) {
                    if (res.status) {
                        let data = res.data;
                        let dia = dialog({
                            title: '查看详细内容',
                            content: `<form action="${action}">
<div class="form-row"><div class="label">邮箱：</div><div class="form-text">${data.email}</div></div>
<div class="form-row"><div class="label">时间：</div><div class="form-text">${data.addTime}</div></div>
<div class="form-row"><div class="label">IP：</div><div class="form-text">${data.ip}</div></div>
<div class="form-row"><div class="label">内容：</div><div class="form-text">${data.content}</div></div>
<div class="form-row"><div class="label">回复：</div><textarea name="response" class="form-text">${data.response && data.response.content || ''}</textarea><input type="hidden" name="as" value="作者"><input type="hidden" name="email" value="${data.email}"></div>
</form>`,
                            ok: function () {
                                let $form = $(dia.node).find('form');
                                $.post($form.attr('action'), $form.serialize(), function (res) {
                                    console.log(res)
                                })
                            },
                            okValue: '确定'
                        }).showModal();
                    }
                });

            });


            $('.js-reboot').click(function (e) {
                $.get($(this).data('url'), function (res) {
                    if (res.status) {
                        let base = 0;
                        let flag = setInterval(function () {
                            base += 20;
                            $('.process-bar').width(base + '%');
                            $('.process-bar span').text(base + '%');
                            if (base == 100) {
                                clearInterval(flag);
                                window.location.reload();
                            }
                        }, 1000);
                    }
                })
            })
        },
        upload: function (option) {
            let that = this;
            let uploader = WebUploader.create({
                // 选完文件后，是否自动上传。
                auto: option.auto || true,
                // 文件接收服务端。
                server: option.url || $(option.ele).data('upload'),
                pick: option.ele,
                fileVal: option.name,
                // 只允许选择图片文件。
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png',
                    mimeTypes: 'image/*'
                }
            });
            uploader.on('uploadSuccess', function (file, res) {
                option.success && option.success(file, res)
            });
        },
        uploadLib: function (setting) {
            let that = this;
            let dia = dialog({
                id: 'progress',
                width: 698,
                title: '选择' + setting.text,
                content: '<div class="table-header clf"><div class="table-header-fl">' +
                '<a class="button-small button-light mf-ml16" target="_blank" href="/admin/album/1">管理' + setting.text + '</a>' +
                '</div></div>' + '<div class="lib-list"><ul class="clf"></ul></div>' +
                '<div class="library-uploader-bar">' +
                '<div class="library-checked-count">已选择<span class="js-checked-num">' + setting.paths.length + '</span>/<span class="js-checked-total">' + setting.number + '</span></div>' +
                '</div>' +
                '<div class="library-uploader-content">' +
                '<div class="library-uploader-list"></div>' +
                '<div class="u-page">' +
                ' </div>' +
                '</div>',
                okValue: '保存',
                ok: function () {
                    let $selected = ($(dia.node).find('.lib-list li.selected'));
                    let data = [];
                    for (let k = 0; k < $selected.length; k++) {
                        data.push($selected.eq(k).data('url'));
                    }
                    setting.callback && setting.callback(data, dia);
                },
                cancelValue: '取消',
                cancel: function () {
                },
                onshow: function () {
                    that.getAlbumLib('/album/lib/1', function (res) {
                        let $ul = $(dia.node).find('.lib-list ul');
                        $ul.html(res.data.content);
                        let $page = $(dia.node).find('.u-page');
                        $page.html(res.data.upage);
                    });
                    $(dia.node).on('click', '.lib-list li', function () {
                        let counter = $(dia.node).find('.js-checked-num');

                        if ($(this).hasClass('selected')) {
                            $(this).removeClass('selected');
                            counter.text($(dia.node).find('.lib-list li.selected').length)
                        }
                        else {
                            if ($(dia.node).find('.lib-list li.selected').length < setting.number) {
                                $(this).addClass('selected');
                                counter.text($(dia.node).find('.lib-list li.selected').length)
                            }
                        }
                    });
                    $(dia.node).on('click', '.u-page a', $(dia.node), function () {
                        let url = $(this).data('url');
                        that.getAlbumLib(url, function (res) {
                            let $ul = $(dia.node).find('.lib-list ul');
                            $ul.html(res.data.content);
                            let $page = $(dia.node).find('.u-page');
                            $page.html(res.data.upage);
                        })
                    })
                }
                /*},
                zIndex: 100*/
            });
            dia.showModal();
            return dia;
        },
        getAlbumLib: function (url, cbk) {
            $.get(url, function (res) {
                cbk && cbk(res);
            });
        },
        handle: function (res) {
            let msg;
            res.status ? msg = '操作成功' : msg = '操作失败';
            $.tipTop(res.status, res.msg || msg);
            setTimeout(function () {
                res.redirect ? window.location.href = res.redirect : window.location.reload();

            }, 1000)
        },
        confirm: function ($ele) {
            let that = this;
            let url = $ele.data('url');
            let dia = dialog({
                'id': 'confirm-dialog',
                'content': '<div class="confirm-tip tip-warn">' +
                '<div class="txt-h4">确定删除吗？</div>' +
                '<div class="confirm-tip-operate">' +
                '<button class="button-small button-dark">确定</button>' +
                '<button class="button-small button-light">取消</button>' +
                '</div>' +
                '</div>'
            }).showModal();

            $(dia.node).find('.button-dark').click(function () {
                $.get(url, function (res) {
                    that.handle(res);
                })
            });

            $(dia.node).find('.button-light').click(function () {
                dia.remove();
            })
        },
        //编辑器
        editor: function (selector, cbk) {
            let ele = selector || '.tiny';
            tinymce.init({
                selector: '.tiny',
                language: 'zh_CN',
                element_format: 'html',
                encoding: 'html',
                allow_unsafe_link_target: true,
                document_base_url:'https://maiwenbo.com/',
                relative_urls: false,
                fontsize_formats: "12px 14px 16px 18px 24px 28px 36px 48px",
                font_formats: 'PingFang SC=PingFang SC;宋体=SimSun;微软雅黑=Microsoft YaHei;Arial=arial,helvetica,sans-serif;Courier New=courier new,courier;Verdana=Verdana',
                plugins: 'code paste lists table textcolor link media imagetools preview image codesample',
                toolbar: ['code | formatselect | fontselect| fontsizeselect | bold,italic, underline, strikethrough,forecolor , backcolor | alignleft, aligncenter, alignright, alignjustify,bullist, numlist', 'link table media imageSelector undo redo preview codesample'],
                codesample_languages: [
                    {text: 'JavaScript', value: 'javascript'},
                    {text: 'HTML/XML', value: 'markup'},
                    {text: 'CSS', value: 'css'},
                    {text: 'Python', value: 'python'}
                ],
                codesample_content_css:'/static/css/prism.css',
                paste_data_images: true,
                branding: false,
                menubar: false,
                media_alt_source: false,
                media_live_embeds: true,
                formats: {
                    italic: {inline: 'span', styles: {'font-style': 'italic'}},
                    bold: {inline: 'span', styles: {'font-weight': 'bold'}}
                },
                image_title: true,
                images_upload_handler: function (blobInfo, success, failure) {
                    let formData = new FormData();
                    formData.append('img', blobInfo.blob());
                    $.ajax({
                        url: '/upload/img',
                        method: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            success( res.data);
                        }
                    })

                },
                init_instance_callback: function (editor) {
                    editor.on('KeyUp', function (e) {

                        tinyMCE.triggerSave();
                        cbk && cbk(editor);
                    });
                    editor.on('NodeChange', function (e) {

                        tinyMCE.triggerSave();
                    });
                }
            });
        }
    };
    admin.init();
});
